package com.jlc.book.shop.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jlc.book.shop.delegate.UserDelegate;
import com.jlc.book.shop.to.UserTO;
import com.jlc.book.shop.validator.JLCDataValidator;

public class UpdateInfoAction {

	public String updateUserInfo(HttpServletRequest request,
			HttpServletResponse response) {
		
		boolean isError=false;
		String page="detailsDef.jsp";
		String email=request.getParameter("email");
		String phone=request.getParameter("phone");
		
		
		request.setAttribute("EMAIL", email);
		request.setAttribute("PHONE", phone);
		
		if(!JLCDataValidator.validateRequired(email))
		{
			request.setAttribute("email", "Email is required");
			isError=true;
		}
		else if(!JLCDataValidator.maxLength(phone, 32))
		{
			request.setAttribute("email", "Email must be maximum 32 character");
			isError=true;
		}
		
		else if(!JLCDataValidator.validateEmail(email))
		{
			request.setAttribute("email", "Please enter valid email id");
			isError=true;
		}
		

		if(!JLCDataValidator.validateRequired(phone))
		{
			request.setAttribute("phone", "Phone is required");
			isError=true;
		}
		else if(!JLCDataValidator.validateLong(phone))
		{
			request.setAttribute("phone", "Phone must be digits only");
			isError=true;
			
		}
		else if(!JLCDataValidator.minLength(phone, 10))
		{
			request.setAttribute("phone", "Phone must be 10 digits");
			isError=true;
		}
		
		if(!isError)
		{
			boolean updated=false;
			Object obj=request.getSession().getAttribute("USER_TO");
			UserTO uto=(UserTO) obj;
			System.out.println(uto.getUserId());
			
			updated=UserDelegate.updateUserInfo(uto.getUserId(),email,Long.parseLong(phone));
			
			if(updated)
			{
				request.setAttribute("updateError", "Information updated successfully");
				request.getSession().removeAttribute("EDIT_INFO");
				uto.setEmail(email);
				uto.setPhone(Long.parseLong(phone));
				request.getSession().setAttribute("USER_TO",uto);
			}
			else
			{
				request.setAttribute("updateError", "Error occured while updating the information.Please try later");
				
			}
			
		}
		
		
		return page;
	}

}
